<?php

namespace App\Http\Service\Baoliao;

use App\Models\Baoliaopost;
use App\Models\Baoliaolike;
use App\Models\Baoliaocollect;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use App\Http\Service\BaseService;
use App\Http\Service\ContentScoringService;
use App\Models\Baoliaolog;
use App\Http\Service\UserService;
use App\Http\Service\Baoliao\BaoliaoService;
use App\Http\Service\MoneyService;
use App\Http\Service\PlatformsService;
use App\Http\Service\SiteConfigService;
use App\Http\Service\PostaiService;
use App\Http\Service\Brand\CategorymappingService;
use App\Http\Service\Brand\BrandmappingService;
use App\Models\Doubanpostproduct;
use App\Models\Doubanpost;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

use App\Http\Service\Douban\DoubanpostproductService;
class BaoliaoDetailfanganService  extends BaseService
{
    private $url;
    private $getInfo;
    private $model;
    public $URL_MAP;
    public function __construct(Baoliaopost $model,Baoliaolog $baoliaolog,UserService  $userService,PlatformsService $platformsService,SiteConfigService $siteConfigService,Doubanpostproduct $doubanpostproduct,DoubanpostproductService $DoubanpostproductService,PostaiService $postaiService,Doubanpost $doubanpost,MoneyService $moneyService,CategorymappingService $categorymappingService,BrandmappingService $brandmappingService,BaoliaoService $baoliaoService)
    {
        parent::__construct();
        $this->model = $model;
        $this->userService=$userService;
        $this->platformsService=$platformsService;
        $this->baoliaolog=$baoliaolog;
        $this->siteConfigService=$siteConfigService;
        $this->doubanpostproduct=$doubanpostproduct;
        $this->DoubanpostproductService=$DoubanpostproductService;
        $this->url=config('myurl.link-batch-parse.url');
        $this->getInfo=config('myurl.getInfo');
        $this->URL_MAP=config('myurl.URL_MAP');
        $this->postaiService=$postaiService;
        $this->doubanpost=$doubanpost;
        $this->moneyService=$moneyService;
        $this->categorymappingService=$categorymappingService;
        $this->brandmappingService=$brandmappingService;
        $this->baoliaoService=$baoliaoService;

    }
   
    

    // class =1 爆料  2.调用其他详情  3. guangguang
    public function dataDetailfangan($request, $data = [])
    {
        try {
            // 基础参数提取
            $baseParams = $this->extractBaseParams($data, $request);
            extract($baseParams); // people_id, platform_name, item_type, product_id, qb_product_id

            // 获取爆料数据
            $baoliaoData = $this->getBaoliaoData($request, $data);
           // dd($baoliaoData['is_expired']);
            
            // 获取AI数据
            $aiData = $this->getAIData($request, $data, $baoliaoData['is_expired']);
            
            //dd($aiData);
            // 获取逛逛数据
            $guangguangData = $this->getGuangguangData($request, $data);
            
            // 构建返回结果
            return $this->buildResult($baoliaoData, $aiData, $guangguangData, $platform_name);
            
        } catch (\Exception $e) {
            Log::error('获取优化数据失败: ' . $e->getMessage(), ['data' => $data]);
            return $this->getDefaultResult();
        }
    }

    /**
     * 提取基础参数
     */
    private function extractBaseParams($data, $request)
    {
        return [
            'people_id' => $data['people_id'] ?? '',
            'platform_name' => $data['platform_name'] ?? '',
            'item_type' => $data['item_type'] ?? 1,
            'product_id' => $data['product_id'] ?? '',
            'qb_product_id' => $request->input("unique_id", "")
        ];
    }

    /**
     * 获取爆料数据
     */
    private function getBaoliaoData($request, $data)
    {
        $unique_id=$request->input("unique_id");

        /*$where = [
            ['product_id', '=', $unique_id],
            ['platform_name', '=', $data['platform_name']],
        ];
        $first = DB::table('vw_baoliao_post_all')->where($where)->first();
        
        $product_unique_id=$first->product_unique_id;
        //dd($product_unique_id);
        $where2 = [
            ['product_unique_id', '=', $product_unique_id],
            ['platform_name', '=', $data['platform_name']],
        ];

        $list = DB::table('vw_baoliao_post_all')->where($where2)
            ->select([
                'unit_price', 'publish_time', 'commission_rate', 'commission_amount', 
                'unique_id', 'user_id', 'avatar', 'nickname', 'create_time', 
                'start_time', 'end_time', 'title', 'is_owner', 'subsidy_rate'
            ])
            ->get()
            ->map(function ($item) {
                return (array)$item; // 将 stdClass 转换为数组
            })
            ->toArray();*/

    
        // 一次查询获取所有相关数据
        $list = DB::table('vw_baoliao_post_all')
        ->where(function ($query) use ($unique_id, $data) {
            $query->where('product_id', $unique_id)
                  ->orWhere('product_unique_id', $unique_id);
        })
        ->where('platform_name', $data['platform_name'])
        ->select([
            'unit_price', 'publish_time', 'commission_rate', 'commission_amount', 
            'unique_id', 'user_id', 'avatar', 'nickname', 'create_time', 
            'start_time', 'end_time', 'title', 'is_owner', 'subsidy_rate',
            'product_id', 'product_unique_id'
        ])
        ->get()
        ->map(function ($item) {
            return (array)$item;
        })
        ->toArray();
        //dd($list);
        $promotion_plan = [];
        $baoliao_content = [];
        $is_expired = 2;
        $has_valid_baoliao = false;

        foreach ($list as $k => &$v) {
            $v = $this->processBaoliaoItem($v, $data);
            
            // 检查是否在3天内
            $publish_time = $v['publish_time'];
            $day_3 = date('Y-m-d H:i:s', strtotime('-3 days'));
            
            if ($publish_time >= $day_3) {
                $is_expired = $this->checkAndUpdateExpiredStatus($v, $is_expired);
                if ($is_expired == 2) {
                    $has_valid_baoliao = true;
                    $promotion_plan[] = $v;
                }
            }
            
            $baoliao_content[] = $v;
        }

        // 如果3天内没有有效爆料，则标记为过期
        if (empty($promotion_plan) || !$has_valid_baoliao) {
            $is_expired = 1;
        }

        return [
            'promotion_plan' => $promotion_plan,
            'baoliao_content' => $baoliao_content,
            'is_expired' => $is_expired
        ];
    }

    /**
     * 处理单个爆料项
     */
    private function processBaoliaoItem($item, $data)
    {
        $item['type'] = 'baoliao';
        $item['qb_product_id'] = $data['product_id'];
        $item['platform'] = $data['platform_name'];
        $item['class'] = 1;
        $item['user_id'] = $data['people_id'];
        
        $is_owner = $item['is_owner'] ?? 1;
        $commission_rate = $item['commission_rate'] ?? 0.00;
        $subsidy_rate = $item['subsidy_rate'] ?? 0.00;

        // 计算预估佣金
        $estimatedCommission = $this->moneyService->estimatedTotalCommission(
            $item['unit_price'],
            $subsidy_rate,
            $commission_rate,
            $data['platform_name'],
            $data['people_id'],
            1,
            $is_owner,
            $data['item_type']
        );

        $item['commission_amount'] = _round($estimatedCommission['total_commission']);
        
        return $item;
    }

    /**
     * 检查并更新过期状态
     */
    private function checkAndUpdateExpiredStatus($item, $currentStatus)
    {
        $currentTime = time();
        $startTime = strtotime($item['start_time']);
        $endTime = strtotime($item['end_time']);

        if ($currentTime >= $startTime && $currentTime <= $endTime) {
            return 2; // 未过期
        } else {
            // 标记为过期
            $this->model->where(['unique_id' => $item['unique_id']])
                ->update([
                    'is_expired' => 1,
                    'update_time' => date("Y-m-d H:i:s")
                ]);
            return 1; // 已过期
        }
    }

    /**
     * 或者更精确的版本，考虑业务特点
     */
    private function getDailyCacheExpireTime()
    {
        $now = time();
        $currentHour = date('H');
        
        // 如果是晚上（18点后），缓存时间可以短一些，因为接近第二天
        if ($currentHour >= 18) {
            $tomorrow = strtotime('tomorrow 06:00:00'); // 第二天早上6点
        } else {
            $tomorrow = strtotime('tomorrow 00:00:00'); // 第二天0点
        }
        
        return $tomorrow - $now;
    }

    /**
     * 获取AI数据
     */
    private function getAIData($request, $data, $is_expired)
    {
        // 生成缓存键
        $time=date('Y-m-d');
        $cacheKey = 'ai_data:' . md5($data['product_id'] . '_' . $data['platform_name'] . '_' . $time);
        $cacheTime = $this->getDailyCacheExpireTime();//过期时间
        // 尝试从缓存获取

        
        $getinfo_url = $this->getInfo;
        $user_params = [
            "product_id" => $data['product_id'],
            "platform" => $data['platform_name'],
            "user_id" => $data['people_id']
        ];
        #ceshi
        //$data = Cache::pull($cacheKey);

        $cachedData = Cache::get($cacheKey);
        if ($cachedData !== null) {
            $postdata= $cachedData;
           //dd($postdata);
        }else{
            $postdata = json_post($getinfo_url, $user_params);
            // 存入缓存
            Cache::put($cacheKey, $postdata, $cacheTime);
        }
       // dd($postdata);
        
        if (!isset($postdata['status']) || $postdata['status'] != '200' || !isset($postdata['data'])) {
            $result = [
                'userai_data' => [],
                'baoliao_hb' => []
            ];
            // 缓存空结果，避免频繁请求
            Cache::put($cacheKey, $postdata, 300); // 5分钟缓存空结果
            return $result;
        }



        $user_data = $postdata['data'];

        // 处理AI数据
        $userai_data = $this->processAIData($request, $user_data, $data);

        #测试 
        //$is_expired=1;
        
        // 如果需要合并AI数据
        $baoliao_hb = [];
        if ($is_expired == 1) {
            $baoliao_post_data = $this->buildBaoliaoPostData($user_data, $data);
            //dd($baoliao_post_data);
            $baoliao_hb = $this->baoliaoService->perfectInfoParms3($request, $baoliao_post_data);
            //dd($baoliao_hb);
        }

        $result = [
            'userai_data' => $userai_data,
            'baoliao_hb' => $baoliao_hb,
            'user_data' => $user_data
        ];
        
      
        
        return $result;
    }

    /**
     * 处理AI数据
     */
    private function processAIData($request,$user_data, $data)
    {
        $this->userService->update_user($data['people_id']);
        
        // 存储AI数据
        $hdata = [
            'unique_id' => "{$data['product_id']},{$data['platform_name']}",
            'platform_name' => $data['platform_name'],
            'product_id' => $data['product_id'],
            'estimate_commission' => $user_data['commission_rate'] ?? 0,
            'json_data' => json_encode($user_data, JSON_UNESCAPED_UNICODE)
        ];
        
        $ar = platform_name_product_id($data['platform_name'], $hdata['product_id']);
        $hdata['product_unique_id'] = $user_data['product_id_suffix'] ?? $ar['1'];
        
        //dd($hdata);
        $ai_arr = $this->postaiService->addData($request, $hdata);

        //dd($ai_arr);
        
        return [[
            "type" => 'baoliao',
            "title" => $user_data['name'] ?? '',
            "class" => 2,
            "unit_price" => $user_data['final_price'] ?? 0,
            "commission_rate" => $user_data['commission_rate'] ?? 0,
            'commission_amount' => $user_data['commission_rate'] ?? 0,
            'unique_id' => "{$data['product_id']},{$data['platform_name']}",
            'user_id' => $data['people_id'],
            'qb_product_id' => $data['product_id'],
            'platform' => $data['platform_name'],
            'publish_time' => $ai_arr['publish_time'] ?? date('Y-m-d H:i:s'),
            'avatar' => "http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/xingfanapp/uploads/442ca8601a70923b7fdb5d697188f80c3983df5c.png",
            'nickname' => "乐天未来"
        ]];
    }

    /**
     * 构建爆料帖子数据
     */
    private function buildBaoliaoPostData($user_data, $data)
    {
        $commissionData = $this->calculateCommissionData($user_data, $data);
        
        return [
            'avatar' => 'http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/xingfanapp/uploads/442ca8601a70923b7fdb5d697188f80c3983df5c.png',
            'nickname' => '乐天未来',
            'product_id' => $data['product_id'],
            'people_id' => $data['people_id'],
            'article_title' => $user_data['name'] ?? '',
            'shop_id' => $user_data['shop_id'] ?? 0,
            'title' => $user_data['name'] ?? '',
            'platform' => $data['platform_name'],
            'publish_time' => date('Y-m-d H:i:s'),
            'product_unique_id' => $user_data['product_id_suffix'] ?? '',
            'type' => '5',
            'user_id' => '633',
            'content' => $user_data['steps_plan']['duojian_step']['price_desc'] ?? '',
            'purchase_screenshots' => [],
            'cover' => $user_data['img'] ?? '',
            'unit_price' => $user_data['final_price'] ?? 0,
            'subsidy_rate' => $user_data['platform_subsidy'][0]['subsidy_rate'] ?? 0,
            'subsidy_amount' => $user_data['platform_subsidy'][0]['subsidy_amount'] ?? 0,
            'subsidy_name' => $user_data['platform_subsidy'][0]['subsidy_name'] ?? '',
            'is_subsidy' => !empty($user_data['platform_subsidy']) ? 1 : 0,
            'jd_plus_commission_desc' => $user_data['jd_plus_commission_desc'] ?? '',
            'quantity' => 1,
            'images' => $user_data['screen_img'] ?? [],
            'category_id' => null,
            'category_name' => $user_data['standard_category'] ?? '',
            'origain_price' => $user_data['origain_price'] ?? 0,
            'commission_rate' => $user_data['commission_rate'] ?? 0,
            'commission_amount' => $commissionData['commission_amount'],
            'product_unique_id' => $user_data['product_id_suffix'] ?? '',
            'purchase_youhuiquan' => $this->buildPurchaseData($user_data, 'coupon_list', 1),
            'purchase_huodong' => $this->buildPurchaseData($user_data, 'discount_desc', 2),
            'purchase_jiagou' => [],
            'purchase_coudan' => [],
            'start_time' => date('Y-m-d H:i:s'),
            'end_time' => date('Y-m-d 23:59:59'),
            'original_brand_name' => $user_data['original_brand'] ?? '',
            'standard_brand_name' => $user_data['standard_brand'] ?? '',
            'original_category_name' => $user_data['original_category'] ?? '',
            'standard_category_name' => $user_data['standard_category'] ?? '',
            'brand_name' => $user_data['standard_brand'] ?? ''
        ];
    }

    /**
     * 计算佣金数据
     */
    private function calculateCommissionData($user_data, $data)
    {
        $subsidy_rate = $user_data['platform_subsidy'][0]['subsidy_rate'] ?? 0;
        $estimatedCommission = $this->moneyService->estimatedTotalCommission(
            $user_data['final_price'] ?? 0,
            $subsidy_rate,
            $user_data['commission_rate'] ?? 0,
            $data['platform_name'],
            $data['people_id'],
            0,
            true,
            $data['item_type']
        );

        return [
            'commission_amount' => _round($estimatedCommission['total_commission'])
        ];
    }

    /**
     * 构建购买数据
     */
    private function buildPurchaseData($user_data, $field, $type)
    {
        $result = [];
        $typeMap = [1 => '优惠券', 2 => '活动'];
        
        if (isset($user_data['steps_plan']['duojian_step'][$field])) {
            foreach ($user_data['steps_plan']['duojian_step'][$field] as $item) {
                $result[] = [
                    'type' => $type,
                    'title' => $typeMap[$type],
                    'description' => is_array($item) ? ($item['coupon_title'] ?? '') : $item,
                    'link' => is_array($item) ? ($item['coupon_url'] ?? '') : '',
                    'platform' => $user_data['platform'] ?? '',
                ];
            }
        }
        
        return $result;
    }

    /**
     * 获取逛逛数据
     */
    private function getGuangguangData($request, $data)
    {
        $unique_id=$request->input("unique_id");
        #测试
        //$unique_id='xAGxe0JUktqOBJzKO2C6nvFAt9-xnAb4Z8IOZPXvYP6F0';
        
        $where1 = [
            ['product_id', '=', $unique_id],
            ['platform_name', '=', $data['platform_name']],
        ];
        //$this->getLastSql();
        $first=$this->doubanpostproduct->where($where1)->first();
        //dd($where1);
        if(!$first){
            return [
                'guangguang_day3' => [],
                'guangguang_content' => []
            ];
        }
        $product_unique_id=$first->product_unique_id;
        $where = [
            ['A.product_unique_id', '=', $product_unique_id],
            ['A.platform_name', '=', $data['platform_name']],
        ];

        //dd($where);
        $fields = [
            'A.unit_price', 'A.commission_rate', 'A.commission_amount', 'A.unique_id', 
            'A.user_id', 'A.avatar', 'A.nickname', 'A.create_time', 'A.publish_time', 
            'A.post_unique_id', 'B.title', 'A.subsidy_rate', 'A.platform_name'
        ];

        $guangguang_list = $this->doubanpostproduct->select($fields)
            ->from('douban_post_product as A')
            ->join('douban_post as B', 'A.post_unique_id', '=', 'B.unique_id')
            ->where($where)
            ->get()
            ->toArray();

        $guangguang_day3 = [];
        $guangguang_content = [];

        foreach ($guangguang_list as &$v) {
            $v = $this->processGuangguangItem($v, $data);
            
            $publish_time = $v['publish_time'];
            $day_3 = date('Y-m-d H:i:s', strtotime('-3 days'));
            
            if ($publish_time >= $day_3) {
                $guangguang_day3[] = $v;
            }
            
            $guangguang_content[] = $v;
        }

        return [
            'guangguang_day3' => $guangguang_day3,
            'guangguang_content' => $guangguang_content
        ];
    }

    /**
     * 处理逛逛项
     */
    private function processGuangguangItem($item, $data)
    {
        $item['type'] = 'guangguang';
        $item['class'] = '3';
        
        $unit_price = $item['unit_price'] ?? 0.00;
        $subsidy_rate = $item['subsidy_rate'] ?? 0.00;
        $commission_rate = $item['commission_rate'] ?? 0.00;

        $estimatedCommission = $this->moneyService->estimatedTotalCommission(
            $unit_price,
            $subsidy_rate,
            $commission_rate,
            $item['platform_name'],
            $data['people_id'],
            1,
            true,
            $data['item_type']
        );

        $item['commission_amount'] = _round($estimatedCommission['total_commission']);
        
        return $item;
    }

    /**
     * 构建最终结果
     */
    private function buildResult($baoliaoData, $aiData, $guangguangData, $platform_name)
    {
        // 合并方案数据
        $plan_fangan = $baoliaoData['is_expired'] == 1 
            ? array_merge($baoliaoData['promotion_plan'], $aiData['userai_data'])
            : $baoliaoData['promotion_plan'];

        // 合并相关内容
        $baoliao_content = $baoliaoData['baoliao_content'];
        if (!empty($aiData['baoliao_hb'])) {
            $baoliao_content = array_merge(
                $baoliao_content, 
                is_array($aiData['baoliao_hb']) ? $aiData['baoliao_hb'] : [$aiData['baoliao_hb']]
            );
        }

        // 排序
        $plan_fangan = sortByPublishTime(array_values($plan_fangan));
        $baoliao_day3 = sortByPublishTime($plan_fangan);
        $baoliao_content = sortByPublishTime(array_values($baoliao_content));
        $guangguang_day3 = sortByPublishTime($guangguangData['guangguang_day3']);
        $guangguang_content = sortByPublishTime($guangguangData['guangguang_content']);

        // 构建提示信息
        $promotionInfo = $this->buildPromotionInfo($aiData['user_data'] ?? [], $platform_name);

        return [
            'bu_tie_msg' => $promotionInfo['bu_tie_msg'],
            'jd_plus_commission_desc' => $promotionInfo['jd_plus_commission_desc'],
            'promotion_plan' => [
                'plan_fangan' => $plan_fangan,
                'baoliao_day3' => $baoliao_day3,
                'guangguang_day3' => $guangguang_day3,
            ],
            'about_content' => [
                'baoliao_content' => $baoliao_content,
                'guangguang_content' => $guangguang_content,
            ]
        ];
    }

    /**
     * 构建促销信息
     */
    private function buildPromotionInfo($user_data, $platform_name)
    {
        $yong_jin = $user_data['commission'] ?? 0;
        $bu_tie = $user_data['other_rate']['subsidy_rate'] ?? 0;
        $jd_plus_commission_desc = $user_data['jd_plus_commission_desc'] ?? '';

        $bu_tie_msg = ($bu_tie > 0) 
            ? "该商品参与{$platform_name}活动(佣金{$yong_jin}) (补贴{$bu_tie})"
            : '';

        return [
            'bu_tie_msg' => $bu_tie_msg,
            'jd_plus_commission_desc' => $jd_plus_commission_desc
        ];
    }

    /**
     * 获取默认结果
     */
    private function getDefaultResult()
    {
        return [
            'bu_tie_msg' => '',
            'jd_plus_commission_desc' => '',
            'promotion_plan' => [
                'plan_fangan' => [],
                'baoliao_day3' => [],
                'guangguang_day3' => [],
            ],
            'about_content' => [
                'baoliao_content' => [],
                'guangguang_content' => [],
            ]
        ];
    }
    
   
}
